package com.yunfeng.supercall.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.lin.activity.LauncherActivity;
import com.lin.activity.SuperFriendsNearByActivity;
import com.lin.fragments.ExploreFragment;
import com.lin.fragments.MineFragment;
import com.lin.fragments.RecentCallFragment;
import com.lin.fragments.SuperFriendDynamicFragment;
import com.lin.fragments.SuperFriendsFragment;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.lin.utils.Session.SignupResult;
import com.lin.views.CustomViewPager;
import com.lin.views.MyFragmentAdapter;
import com.ly.quickdev.library.activity.BaseFragmentTabActivity;
import com.ly.quickdev.library.adapter.ListBaseAdapter.ViewHolder;
import com.ly.quickdev.library.utils.JsonUtils;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.update.UmengUpdateAgent;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.bean.AdsBean;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.LevelBean;
import com.yunfeng.supercall.bean.LevelColorBean;
import com.yunfeng.supercall.bean.MyCircleBean;
import com.yunfeng.supercall.bean.ShareConfigBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.fragment.RecentChatListFragment;
import com.yunfeng.supercall.fragment.ShareFragment;
import com.yunfeng.supercall.fragment.SuperContactsFragment;
import com.yunfeng.supercall.httputils.HttpClient;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.iface.MessageAccessable;
import com.yunfeng.supercall.manager.CommentCountManager;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;
import com.yunfeng.supercall.service.CallConnectionService;
import com.yunfeng.supercall.service.CallConnectionService.MyBinder;

/**
 * 主页面，管理5个Fragment
 * 
 * @author 洋
 * 
 */
public class MainActivity2 extends BaseActivity implements OnPageChangeListener, OnClickListener{

	/** 存放 */
	public static final Map<String, String> LEVEL_MAPS = new HashMap<String, String>();
	public static final Map<String, LevelColorBean> LEVEL_COLOR_MAPS = new HashMap<String, LevelColorBean>();
	private MessageReceiver mMessageReceiver;
	private String[] mTabTitles;
	Session mSession;
	UserBean userbean;
	RecentCallFragment mRecentFragment;

	private CustomViewPager mViewPager;
	private ImageView imageView1;
	private ImageView imageView2;
	private ImageView imageView3;
	private ImageView imageView4;
	private ImageView imageView5;
	private TextView textview1;
	private TextView textview2;
	private TextView textview4;
	private TextView textview3;
	private TextView textview5;
	private FrameLayout frameLayout1;
	private FrameLayout frameLayout2;
	private FrameLayout frameLayout3;
	private FrameLayout frameLayout4;
	private FrameLayout frameLayout5;
	public static boolean isForeground = false; 
	UpdateBroadcastReceiverFriend mUpdateBroadcastReceiverFriend;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mTabTitles = getResources().getStringArray(R.array.tab_titles);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		isForeground = true;
		mViewPager = (CustomViewPager) findViewById(R.id.mainViewPager);
		mViewPagerRecentCall = (CustomViewPager) findViewById(R.id.mainViewPager_recentcall);
		mLinearLayoutDial = (LinearLayout) findViewById(R.id.linearlayout_dial);
		mTextViewToChat = (TextView) findViewById(R.id.to_chat);
		mButtonChat = (Button) findViewById(R.id.btn_dial);
		mTextViewDelete = (TextView) findViewById(R.id.delete);
		mTextViewDelete.setOnClickListener(onClickListener);
		mButtonChat.setOnClickListener(onClickListener);
		mTextViewToChat.setOnClickListener(onClickListener);
		mTextViewDelete.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				mRecentFragment.onLongClick(v);
				return false;
			}
		});
		/*	mViewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				   if(mViewPager.getCurrentItem()==0)
	                {
					   mViewPager.setScanScroll(false);
	                        return true;        
	                }
				   mViewPager.setScanScroll(true);
	                return false;
			}
		});*/

		mViewPager.setOffscreenPageLimit(4);
		mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);

		imageView1 = (ImageView) findViewById(R.id.imageview1);
		imageView2 = (ImageView) findViewById(R.id.imageview2);
		imageView3 = (ImageView) findViewById(R.id.imageview3);
		imageView4 = (ImageView) findViewById(R.id.imageview4);
		imageView5 = (ImageView) findViewById(R.id.imageview5);


		textview1 = (TextView) findViewById(R.id.textview1);
		textview2 = (TextView) findViewById(R.id.textview2);
		textview3 = (TextView) findViewById(R.id.textview3);
		textview4 = (TextView) findViewById(R.id.textView4);
		textview5 = (TextView) findViewById(R.id.textView5);

		frameLayout1 = (FrameLayout) findViewById(R.id.framelayout1);
		frameLayout2 = (FrameLayout) findViewById(R.id.framelayout2);
		frameLayout3 = (FrameLayout) findViewById(R.id.framelayout3);
		frameLayout4 = (FrameLayout) findViewById(R.id.framelayout4);
		frameLayout5 = (FrameLayout) findViewById(R.id.framelayout5);

		frameLayout1.setOnClickListener(onClickListener);
		frameLayout2.setOnClickListener(onClickListener);
		frameLayout3.setOnClickListener(onClickListener);
		frameLayout4.setOnClickListener(onClickListener);
		frameLayout5.setOnClickListener(onClickListener);

		mImageViewChatRedDot = (ImageView) findViewById(R.id.red_dot_chat);
		mImageViewFriendRedDot = (ImageView) findViewById(R.id.red_dot_friend);

		ArrayList<Fragment> mFragments1 = new ArrayList<Fragment>();
		//		mFragments1.add(new RecentCallFragment());
		mFragments1.add(new RecentChatListFragment());
		mFragments1.add(new SuperFriendsFragment());
		mFragments1.add(new ExploreFragment());
		mFragments1.add(new MineFragment());
		MyFragmentAdapter mFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(),
				mFragments1);
		mViewPager.setAdapter(mFragmentAdapter);

		ArrayList<Fragment> mFragments2 = new ArrayList<Fragment>();
		mFragments2.add(mRecentFragment = new RecentCallFragment());

		MyFragmentAdapter mFragmentAdapter2 = new MyFragmentAdapter(getSupportFragmentManager(),
				mFragments2);
		mViewPagerRecentCall.setAdapter(mFragmentAdapter2);
		//		mViewPagerRecentCall.setOnPageChangeListener(this);
		mViewPager.setOnPageChangeListener(this);
		//		mViewPagerRecentCall.setOnPageChangeListener(this);
		userbean = BaseActivity.getUser(getApplicationContext());

		/** 查询友盟更新 */
		UmengUpdateAgent.update(this);
		/** 注册聊天消息监听器 */
		mMessageReceiver = new MessageReceiver();
		IntentFilter mIntentFilter = new IntentFilter();
		mIntentFilter.addAction(Constants.ACTION_RECEIVE_MSG);
		registerReceiver(mMessageReceiver, mIntentFilter);
		/** 加载一系列数据 */
		loadMyCircle();
		loadShareConfig();
		loadLevels();
		loadLevelColors();
		loadAds();

		/** 开启极光推送 */
		JPushInterface.setLatestNotificationNumber(getApplicationContext(), 3);
		JPushInterface.resumePush(getApplicationContext());
		try {
			String phone =  BaseActivity.getUser(getActivity())
					.getPhone();
			JPushInterface.setAliasAndTags(getApplicationContext(), phone
					, null, new TagAliasCallback() {

				@Override
				public void gotResult(int arg0, String arg1, Set<String> arg2) {
					// TODO Auto-generated method stub
					Log.i("info123", arg1 + "");
				}
			});
		} catch(NullPointerException e) {
			e.printStackTrace();
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			finish();	
		}
		signIn();

		/** 绑定到聊天服务商 */
		bindService(new Intent(this, CallConnectionService.class),
				mServiceConnection, Service.BIND_AUTO_CREATE);
		/** 绑定到聊天服务商 */
		startService(new Intent(this, CallConnectionService.class));
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_NEWFRIEND_MSG);
		mUpdateBroadcastReceiverFriend = new UpdateBroadcastReceiverFriend();
		getActivity().registerReceiver(mUpdateBroadcastReceiverFriend, filter);
		//		startService(new Intent(this, CallConnectionService.class));
		//		startService(new Intent(this, CallConnectionIntentService.class));

		/*	startActivity(new Intent(this,
				SuperFriendsNearByActivity.class));*/

	}




	private void loadAds() {
		// TODO Auto-generated method stub
		try {


			mSession.getSysAd(getApplicationContext(),userbean.getUserid(), new ResultReceiver<ArrayList<AdsBean>>() {

				@Override
				public void onResult(boolean last, ArrayList<AdsBean> mAds) {
					// TODO Auto-generated method stub
					try {
						if(mAds != null)return;
						ManagerFactory.createManager(AdsBean.class).saveList(mAds);
					} catch(Exception e) {

					}
				}

			});
		} catch(NullPointerException e) {
			e.printStackTrace();
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			finish();

		}
	}

	private CallConnectionService mCallConnectionService;
	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mCallConnectionService = ((MyBinder) service).getService();
			mCallConnectionService.setShowNotification(false);
		}
	};

	protected void onPause() {
		super.onPause();
		// if (mCallConnectionService != null) {
		// mCallConnectionService.setShowNotification(true);
		// }
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		String chat = getIntent().getAction();
		if(chat != null && chat.equalsIgnoreCase(FROM_CHAT_NOTIFICATION)) {
			mViewPager.setCurrentItem(0);
			mViewPagerRecentCall.setVisibility(View.INVISIBLE);
			mViewPager.setVisibility(View.VISIBLE);
			mImageViewChatRedDot.setVisibility(View.INVISIBLE);
			imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
			imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_selected));
			imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
			imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
			imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));

			mViewPager.setCurrentItem(0);
			mViewPagerRecentCall.setVisibility(View.INVISIBLE);
			mViewPager.setVisibility(View.VISIBLE);
			mImageViewChatRedDot.setVisibility(View.INVISIBLE);
			textview1.setTextColor(Color.parseColor("#999999"));
			textview2.setTextColor(getResources().getColor(R.color.base_orange));
			textview3.setTextColor(Color.parseColor("#999999"));
			textview4.setTextColor(Color.parseColor("#999999"));
			textview5.setTextColor(Color.parseColor("#999999"));
		}
		// if (mCallConnectionService != null) {
		// mCallConnectionService.setShowNotification(false);
		// }
		NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		manager.cancelAll();
		loadShareCommentCount();

		boolean has = SuperFriendsManager.hasNewFriend(this);
		mImageViewFriendRedDot.setVisibility(has ? View.VISIBLE
				: View.INVISIBLE);
	}

	HttpClient mHttpClient = new HttpClient();
	public int mCommentCount;

	private void loadShareCommentCount() {
		final int count = CommentCountManager.getInstance(getActivity())
				.getMaxId();
		JSONObject json = BaseActivity.getBaseParams(getActivity());
		try {
			json.put("i_maxid", count);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(Constants.FUNCTION_GET_MY_SHARE_COMMENT_COUNT, json,
				new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				try {
					JSONObject json = new JSONObject(data.substring(1,
							data.length() - 1));
					mCommentCount = json.getInt("num");
					int max = json.getInt("maxid");
					Fragment fragment = getSupportFragmentManager()
							.findFragmentByTag(mTabTitles[4]);
					if (fragment != null
							&& fragment instanceof MessageAccessable) {
						((MessageAccessable) fragment).refreshMessage();
					}
					CommentCountManager.getInstance(getActivity())
					.setMaxId(max);
					CommentCountManager.getInstance(getActivity())
					.setCurrentId(count);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	/** 记录登陆信息（登陆天数） */
	private void signIn() {
		try {


			mSession.loginLog(getApplicationContext(), userbean.getUserid(), "android", new ResultReceiver<SignupResult>() {

				@Override
				public void onResult(boolean last, SignupResult args) {
					// TODO Auto-generated method stub

				}

			});
		} catch(NullPointerException e) {
			e.printStackTrace();
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			finish();
		}

	}





	public void onBackPressed() {
		moveTaskToBack(false);
		// Intent i = new Intent();
		// i.addCategory(Intent.CATEGORY_HOME);
		// i.setAction(Intent.ACTION_MAIN);
		// startActivity(i);
	};

	/** 加载等级对应的字体颜色 */
	private void loadLevelColors() {
		try {
			mSession.getSuColorList(getApplicationContext(),userbean.getUserid(), new ResultReceiver<ArrayList<LevelColorBean>>() {

				@Override
				public void onResult(boolean last, ArrayList<LevelColorBean> mLevels) {
					// TODO Auto-generated method stub
					try {
						if(mLevels != null)return;
						ManagerFactory.createManager(LevelColorBean.class)
						.saveList(mLevels);
						LEVEL_COLOR_MAPS.clear();
						for (LevelColorBean level : mLevels) {
							LEVEL_COLOR_MAPS.put(level.getId() + "", level);
						}
					} catch(Exception e) {

					}
				}

			});
		} catch(NullPointerException e) {
			// UCSService.uninit(this);
			stopToLogin();

		}
	}

	private void stopToLogin() {
		stopService(new Intent(this, CallConnectionService.class));
		getLoginManager(getActivity()).logout();
		// System.exit(0);
		startActivity(new Intent(this, LoginActivity.class)
		.addFlags(
				Intent.FLAG_ACTIVITY_CLEAR_TASK
				| Intent.FLAG_ACTIVITY_NEW_TASK).putExtra(
						"autologin", false));
		JPushInterface.setAlias(getApplicationContext(), "",
				new TagAliasCallback() {

			@Override
			public void gotResult(int arg0, String arg1,
					Set<String> arg2) {
			}
		});
		JPushInterface.stopPush(getApplicationContext());
	}

	/**
	 * 加载等级信息
	 */
	/**
	 * 加载等级信息
	 */
	private void loadLevels() {
		JSONObject json = BaseActivity.getBaseParams(getActivity());
		HttpClient mHttpClient = new HttpClient();
		mHttpClient.post(Constants.FUNCTION_LEVELS, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				List<LevelBean> mLevels = JsonUtils.parseList(data, LevelBean.class);
				ManagerFactory.createManager(LevelBean.class).saveList(mLevels);
				LEVEL_MAPS.clear();
				for (LevelBean level : mLevels) {
					LEVEL_MAPS.put(level.getLevelid() + "",
							level.getLevelname());
				}
			}
		});
	}


	/**
	 * 加载分享的内容
	 */
	private void loadShareConfig() {
		try {
			JSONObject json = BaseActivity.getBaseParams(getActivity());
			HttpClient mHttpClient = new HttpClient();
			mHttpClient.post(Constants.FUNCTION_SHARE_CONFIG, json,
					new MyAjaxCallBack() {

				@Override
				public void onReceiveError(String msg, String errorCode) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onReceiveData(String data, String msg) {
					// TODO Auto-generated method stub
					ShareConfigBean.sConfig = JsonUtils.parse(
							data.substring(1, data.length() - 1),
							ShareConfigBean.class);
				}
			});
		} catch(NullPointerException e) {
			stopToLogin();

		}
	}

	/**
	 * 加载我的圈子
	 */
	private void loadMyCircle() {
		try {


			mSession.getQuanziList(getApplicationContext(), userbean.getUserid(), 0, new ResultReceiver<ArrayList<MyCircleBean>> () {

				@Override
				public void onResult(boolean last, ArrayList<MyCircleBean> circles) {
					// TODO Auto-generated method stub
					if(circles != null)return;
					try {
						Collections.sort(circles);
						ManagerFactory.createManager(MyCircleBean.class).saveList(
								circles);
					} catch(Exception e) {

					}
				}

			});
		} catch(NullPointerException e) {
			e.printStackTrace();
			stopToLogin();

		}
	}


	/*@Override
	public Class<? extends Fragment>[] getFragments() {
		// TODO Auto-generated method stub
		return (Class<? extends Fragment>[]) new Class<?>[] {
				SuperFriendsFragment.class, SuperFriendsFragment.class,
				SuperFriendsFragment.class, SuperFriendsFragment.class,
				SuperFriendsFragment.class };
		return (Class<? extends Fragment>[]) new Class<?>[] {
				RecentCallFragment.class, RecentCallFragment.class,
				RecentCallFragment.class, RecentCallFragment.class,
				RecentCallFragment.class };
		return (Class<? extends Fragment>[]) new Class<?>[] {
				ShareFragment.class, ShareFragment.class,
				ShareFragment.class, ShareFragment.class,
				ShareFragment.class };

		return (Class<? extends Fragment>[]) new Class<?>[] {
				RecentCallFragment.class, RecentChatListFragment.class, SuperFriendsFragment.class, 
				ExploreFragment.class, 
				MineFragment.class };

		return (Class<? extends Fragment>[]) new Class<?>[] {
				DialPadFragment.class, RecentCallFragment.class, SuperFriendsFragment.class, 
				ExploreFragment.class, 
				MineFragment.class };


	}*/

	/**
	 * 切换拨号面板可见性
	 * 
	 * @author 洋
	 * 
	 */
	public static interface DialPadSwitch {
		void toggle();
		void toggleUp();
	}

	/** 小红点 */
	private ImageView mImageViewChatRedDot, mImageViewFriendRedDot;

	/*	@Override
	public View getIndicatorView(int position) {
		// TODO Auto-generated method stub
		if (position == 0) {
			View v = super.getIndicatorView(position);
			TextView tv = ViewHolder.get(v, R.id.title);
			tv.setTextColor(getResources().getColorStateList(R.color.tab_text));
			v.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					int index = mFragmentTabHost.getCurrentTab();
					if (index != 0) {
						return false;
					}
					switch (event.getActionMasked()) {
					case MotionEvent.ACTION_CANCEL:
					case MotionEvent.ACTION_UP:
						Fragment fragment = getSupportFragmentManager()
						.findFragmentByTag(mTabTitles[0]);
						if (fragment instanceof DialPadSwitch) {
							((DialPadSwitch) fragment).toggle();
						}
						break;

					default:
						break;
					}
					return false;
				}
			});
			return v;
		}
		if (position == 1) {
			View v = getLayoutInflater().inflate(
					R.layout.tab_indicator_view_with_red_dot, null);
			TextView tv = ViewHolder.get(v, R.id.title);
			tv.setText(getTabTitles()[position]);
			ImageView iv = ViewHolder.get(v, R.id.icon);
			iv.setImageResource(getTabIcons()[position]);
			mImageViewChatRedDot = ViewHolder.get(v, R.id.red_dot);
			mImageViewChatRedDot.setVisibility(View.GONE);
			tv.setTextColor(getResources().getColorStateList(R.color.tab_text));
			return v;
		}
		if (position == 2) {
			View v = getLayoutInflater().inflate(
					R.layout.tab_indicator_view_with_red_dot, null);
			TextView tv = ViewHolder.get(v, R.id.title);
			tv.setText(getTabTitles()[position]);
			ImageView iv = ViewHolder.get(v, R.id.icon);
			iv.setImageResource(getTabIcons()[position]);
			mImageViewFriendRedDot = ViewHolder.get(v, R.id.red_dot);
			mImageViewFriendRedDot.setVisibility(View.GONE);
			tv.setTextColor(getResources().getColorStateList(R.color.tab_text));
			return v;
		}
		View v = super.getIndicatorView(position);
		TextView tv = ViewHolder.get(v, R.id.title);
		tv.setTextColor(getResources().getColorStateList(R.color.tab_text));
		return v;
	}
	 */
	/*
	@Override
	public void onTabChanged(String tabId) {
		// TODO Auto-generated method stub
		super.onTabChanged(tabId);
		int index = mFragmentTabHost.getCurrentTab();
		if (index == 1) {
			mImageViewChatRedDot.setVisibility(View.GONE);
		}
	}
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mMessageReceiver);
		isForeground = false;
		if(mUpdateBroadcastReceiverFriend != null) {
			unregisterReceiver(mUpdateBroadcastReceiverFriend);
		}
		//		unbindService(mServiceConnection);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (Constants.ACTION_RECEIVE_MSG.equals(action)) {
				//				int index = mFragmentTabHost.getCurrentTab();
				int index = mViewPager.getCurrentItem();
				if (index != 0 || mViewPagerRecentCall.getVisibility() == View.VISIBLE) {
					mImageViewChatRedDot.setVisibility(View.VISIBLE);
				}
				Fragment fragment = getSupportFragmentManager()
						.findFragmentByTag(mTabTitles[1]);
				if (fragment != null && fragment instanceof MessageAccessable) {
					((MessageAccessable) fragment).refreshMessage();
				}
			}
		}

	}

	/** 腾讯分享回调接口 */
	public static IUiListener qZoneShareListener = new IUiListener() {

		@Override
		public void onCancel() {
		}

		@Override
		public void onError(UiError e) {
			// TODO Auto-generated method stub
			System.out.println("MainActivity.enclosing_method()"
					+ e.errorMessage);
		}

		@Override
		public void onComplete(Object response) {
			// TODO Auto-generated method stub
			System.out.println("MainActivity.enclosing_method()"
					+ response.toString());
		}

	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
			if (resultCode == com.tencent.connect.common.Constants.ACTIVITY_OK) {
				Tencent.handleResultData(data, qZoneShareListener);// 腾讯分享接口
			}
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		/*		if(position == 0) {
			imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_selected));
			imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_normal));
			imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
			imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
			imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));

			textview1.setTextColor(getResources().getColor(R.color.base_orange));
			textview2.setTextColor(Color.parseColor("#999999"));
			textview3.setTextColor(Color.parseColor("#999999"));
			textview4.setTextColor(Color.parseColor("#999999"));
			textview5.setTextColor(Color.parseColor("#999999"));

		} else */if(position == 0) {
			imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
			imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_selected));
			imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
			imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
			imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));

			mImageViewChatRedDot.setVisibility(View.INVISIBLE);
			textview1.setTextColor(Color.parseColor("#999999"));
			textview2.setTextColor(getResources().getColor(R.color.base_orange));
			textview3.setTextColor(Color.parseColor("#999999"));
			textview4.setTextColor(Color.parseColor("#999999"));
			textview5.setTextColor(Color.parseColor("#999999"));
		} else if(position == 1) {
			mImageViewFriendRedDot.setVisibility(View.INVISIBLE);
			imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
			imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_normal));
			imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_selected));
			imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
			imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));


			textview1.setTextColor(Color.parseColor("#999999"));
			textview2.setTextColor(Color.parseColor("#999999"));
			textview3.setTextColor(getResources().getColor(R.color.base_orange));
			textview4.setTextColor(Color.parseColor("#999999"));
			textview5.setTextColor(Color.parseColor("#999999"));
		} else if(position == 2) {
			imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
			imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_normal));
			imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
			imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_selected));
			imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));


			textview1.setTextColor(Color.parseColor("#999999"));
			textview2.setTextColor(Color.parseColor("#999999"));
			textview3.setTextColor(Color.parseColor("#999999"));
			textview4.setTextColor(getResources().getColor(R.color.base_orange));
			textview5.setTextColor(Color.parseColor("#999999"));
		} else if(position == 3) {
			imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
			imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_normal));
			imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
			imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
			imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_selected));


			textview1.setTextColor(Color.parseColor("#999999"));
			textview2.setTextColor(Color.parseColor("#999999"));
			textview3.setTextColor(Color.parseColor("#999999"));
			textview4.setTextColor(Color.parseColor("#999999"));
			textview5.setTextColor(getResources().getColor(R.color.base_orange));
		}

	}


	boolean isClicked = false;
	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			//			mViewPager.setScanScroll(true);
			if(v == frameLayout1) {
				/*if(mViewPagerRecentCall.getCurrentItem() != 0) {
					mRecentFragment.toggleUp();
				} else {
					mRecentFragment.toggle();
				}*/


				if(mViewPagerRecentCall.getVisibility() == View.VISIBLE) {
					mRecentFragment.toggle();
				} else {
					mRecentFragment.toggleUp();
				}
				imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_selected));
				imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_normal));
				imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
				imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
				imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));

				textview1.setTextColor(getResources().getColor(R.color.base_orange));
				textview2.setTextColor(Color.parseColor("#999999"));
				textview3.setTextColor(Color.parseColor("#999999"));
				textview4.setTextColor(Color.parseColor("#999999"));
				textview5.setTextColor(Color.parseColor("#999999"));
				mViewPagerRecentCall.setVisibility(View.VISIBLE);
				mViewPager.setVisibility(View.INVISIBLE);

				//				mViewPagerRecentCall.setCurrentItem(0);
			} else if(v == frameLayout2) {
				if(isClicked == false) {
					sendBroadcast(new Intent(Constants.ACTION_RECEIVE_MSG2));
					isClicked = true;
				}
				imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
				imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_selected));
				imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
				imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
				imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));

				mViewPager.setCurrentItem(0);
				mViewPagerRecentCall.setVisibility(View.INVISIBLE);
				mViewPager.setVisibility(View.VISIBLE);
				mImageViewChatRedDot.setVisibility(View.INVISIBLE);
				textview1.setTextColor(Color.parseColor("#999999"));
				textview2.setTextColor(getResources().getColor(R.color.base_orange));
				textview3.setTextColor(Color.parseColor("#999999"));
				textview4.setTextColor(Color.parseColor("#999999"));
				textview5.setTextColor(Color.parseColor("#999999"));

			} else if(v == frameLayout3) {
				mViewPager.setCurrentItem(1);
				mViewPagerRecentCall.setVisibility(View.INVISIBLE);
				mViewPager.setVisibility(View.VISIBLE);
				imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
				imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_normal));
				imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_selected));
				imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
				imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));

				mImageViewChatRedDot.setVisibility(View.INVISIBLE);
				textview1.setTextColor(Color.parseColor("#999999"));
				textview2.setTextColor(Color.parseColor("#999999"));
				textview3.setTextColor(getResources().getColor(R.color.base_orange));
				textview4.setTextColor(Color.parseColor("#999999"));
				textview5.setTextColor(Color.parseColor("#999999"));

			} else if(v == frameLayout4) {
				mViewPager.setCurrentItem(2);
				mViewPagerRecentCall.setVisibility(View.INVISIBLE);
				mViewPager.setVisibility(View.VISIBLE);
				imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
				imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_normal));
				imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
				imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_selected));
				imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_normal));

				mImageViewChatRedDot.setVisibility(View.INVISIBLE);
				textview1.setTextColor(Color.parseColor("#999999"));
				textview2.setTextColor(Color.parseColor("#999999"));
				textview3.setTextColor(Color.parseColor("#999999"));
				textview4.setTextColor(getResources().getColor(R.color.base_orange));
				textview5.setTextColor(Color.parseColor("#999999"));


			} else if(v == frameLayout5) {
				mViewPager.setCurrentItem(3);
				mViewPagerRecentCall.setVisibility(View.INVISIBLE);
				mViewPager.setVisibility(View.VISIBLE);
				imageView1.setImageDrawable(getResources().getDrawable(R.drawable.ic_dial_normal));
				imageView2.setImageDrawable(getResources().getDrawable(R.drawable.ic_chat_normal));
				imageView3.setImageDrawable(getResources().getDrawable(R.drawable.ic_super_friend_normal));
				imageView4.setImageDrawable(getResources().getDrawable(R.drawable.ic_share_normal));
				imageView5.setImageDrawable(getResources().getDrawable(R.drawable.ic_me_selected));


				textview1.setTextColor(Color.parseColor("#999999"));
				textview2.setTextColor(Color.parseColor("#999999"));
				textview3.setTextColor(Color.parseColor("#999999"));
				textview4.setTextColor(Color.parseColor("#999999"));
				textview5.setTextColor(getResources().getColor(R.color.base_orange));

			} else if(v == mTextViewDelete) {
				mRecentFragment.onClick(v);
			} else if(v == mButtonChat) {
				mRecentFragment.onClick(v);
			} else if(v == mTextViewToChat) {
				//				mRecentFragment.onClick(v);
				mLinearLayoutDial.setVisibility(View.GONE);
			}
		}
	};
	private CustomViewPager mViewPagerRecentCall;
	public LinearLayout mLinearLayoutDial;
	private TextView mTextViewToChat;
	private Button mButtonChat;
	private TextView mTextViewDelete;
	class UpdateBroadcastReceiverFriend extends BroadcastReceiver {

		public UpdateBroadcastReceiverFriend() {

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Log.i("jpsuh", "update data");
			boolean has = SuperFriendsManager.hasNewFriend(MainActivity2.this);
			mImageViewFriendRedDot.setVisibility(has ? View.VISIBLE
					: View.INVISIBLE);
		}

	}
}
